//
//  SearchController.m
//  MY Project For Sport
//
//  Created by admin on 16/2/14.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "SearchController.h"
#import "BaseCollectionViewCellForNews.h"
#import "NetworkingHandlerOfBlock.h"
#import "ModelForSearch.h"
#import "CellForSearch.h"
#import <DKNightVersion.h>
#import "CollectionCellForCell.h"
#import "UIColor+Wonderful.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

#define WEIGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667


@interface SearchController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UIView *viewForNail;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UISearchBar *search;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arrDict;
@property (nonatomic, retain) UICollectionView *collection;

@end

@implementation SearchController

- (void)dealloc {
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"delect" object:nil];
    [_viewForNail release];
    [_button release];
    [_search release];
    [_url release];
    [_array release];
    [_tableView release];
    [_arrDict release];
    [_collection release];
    [super dealloc];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"搜索";
    
    if (! self.arrDict) {
        
        NSString* path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"search1.plist"];
        
        //  NSLog(@"%@", path);
        self.arrDict = [NSMutableArray arrayWithContentsOfFile:path];
        
        if (! self.arrDict ) {
            // NSLog(@"ddd");
            self. arrDict = [NSMutableArray array];
        }
    }
    
    [self createSubview];
    
}


- (void)createSubview {
    
    
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor deepSkyBlue], [UIColor lightGrayColor]);
    
    // collection 显示搜索历史
    
    UILabel *labelForTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 74 + self.view.frame.size.height / 15, self.view.frame.size.width, 30)];
    [self.view addSubview:labelForTitle];
    [labelForTitle release];
    labelForTitle.text = @"搜索历史";
    labelForTitle.font = [UIFont systemFontOfSize:17];
    
    UICollectionViewFlowLayout *flayout = [[UICollectionViewFlowLayout alloc] init];
    flayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flayout.sectionInset = UIEdgeInsetsMake(10 * WEIGHTT, 10 * HEIGHTT, 10 * WEIGHTT, 10 * HEIGHTT);
    
    flayout.minimumInteritemSpacing = 10 * WEIGHTT;
    flayout.minimumLineSpacing = 10 * HEIGHTT;
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 103 + self.view.frame.size.height / 15, self.view.frame.size.width, self.view.frame.size.height - 152 - self.view.frame.size.height / 15) collectionViewLayout:flayout];
    [flayout release];
    [self.view addSubview:self.collection];
    self.collection.pagingEnabled = YES;
    self.collection.dk_backgroundColorPicker = DKColorWithRGB (0xffffff, 0x343434);
    [_collection release];
    //  self.collection.backgroundColor = [UIColor redColor];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.showsHorizontalScrollIndicator = NO;
    
    [self.collection registerClass:[CollectionCellForCell class] forCellWithReuseIdentifier:@"poolForCollection"];
    [self createLongPress];
    
    
    // 删除指定历史 更新 collection
    [[NSNotificationCenter defaultCenter] addObserverForName:@"delect" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        // NSLog(@"note %@",[note.userInfo objectForKey:@"index"]);
        NSString* path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"search1.plist"];
        [self.arrDict removeObject:[note.userInfo objectForKey:@"index"]];
        [self.arrDict writeToFile:path atomically:YES];
        
        [self.collection reloadData];
        
    }];
    
    // 创建搜索栏
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width / 4 * 3, self.view.frame.size.height / 15)];
    self.search.dk_backgroundColorPicker = DKColorWithColors([UIColor grayColor], [UIColor lightGrayColor]);
    [self.view addSubview:self.search];
    [_search release];
    self.search.placeholder = @"输入需要搜索的内容";
    
    // tableView
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + self.view.frame.size.height / 15, self.view.frame.size.width, self.view.frame.size.height - 113 - self.view.frame.size.height / 15) style:UITableViewStylePlain];
    self.tableView.hidden = YES;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[CellForSearch class] forCellReuseIdentifier:@"poolForSearch"];
    
    
    // 确定搜索按键
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake(self.view.frame.size.width / 4 * 3, 64, self.view.frame.size.width / 4, self.view.frame.size.height / 15);
    [self.view addSubview:self.button];
    self.button.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.73 green:0.73 blue:0.73 alpha:1], [UIColor grayColor]);
    [self.button setTitle:@"确定" forState:UIControlStateNormal];
    
    [self.button addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 创建返回上一个界面的 button
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.button.frame = CGRectMake(5 * WEIGHTT, 5 * HEIGHTT, 30 * WEIGHTT, 30 * HEIGHTT);
    [self.navigationController.navigationBar addSubview:self.button];
    [self.button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    
}

/** collection 根据搜索输入的内容自适应宽度*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *str = self.arrDict[indexPath.item];
    
    return CGSizeMake( [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}].width + 50 * WEIGHTT, 40 * HEIGHTT);
    
}

/**添加长按手势*/
- (void)createLongPress {
    
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLong:)];
    [self.collection addGestureRecognizer:longPress];
    [longPress release];
    
}

- (void)handleLong:(UILongPressGestureRecognizer *) longPress {
    
    //  NSLog(@"ddd");
    switch (longPress.state) {
            
        case UIGestureRecognizerStateBegan:
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"showDelete" object:nil userInfo:nil];
            
            break;
            
        } case UIGestureRecognizerStateChanged:{
            
            [self.collection updateInteractiveMovementTargetPosition:[longPress locationInView:self.collection]];
            
            break;
        }case UIGestureRecognizerStateEnded: {
            
            [self.collection endInteractiveMovement];
            
            break;
        }
            
            
        default:
        {
            [self.collection cancelInteractiveMovement];
        }
            break;
    }
    
}

-(void)searchAction:(UIButton *) button {
    
    self.tableView.hidden = NO;
    self.collection.hidden = YES;
    
    if ([self.search.text isEqualToString:@""]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"输入为空或无效字符" preferredStyle: UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            
        }];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        
        
        
    } else {
        
        NSString* path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]
                          stringByAppendingPathComponent:@"search1.plist"];
        
        [self.arrDict addObject:self.search.text];
        
        [self.arrDict writeToFile:path atomically:YES];
        
        [self.view endEditing:YES];
        
        // 如果有中文将搜索的内容进行转码
        NSString *temp = [self.search.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        // NSLog(@"%@", temp);
        
        NSString *url = @"http://api.search.sina.com.cn/?q=";
        NSString *url2 = @"&col=1_10&c=news&t=2_3_5_6&sort=rel&highlight=1&page=1&num=30";
        
        self.url = [url stringByAppendingFormat:@"%@%@", temp, url2];
        // NSLog(@"%@", self.url);
        
        [NetworkingHandler networkingWithUrl:self.url completeHandle:^(NSURLResponse *response, NSData *data, id result) {
            
            self.array = [NSMutableArray array];
            
            NSDictionary *dic = [result objectForKey:@"result"];
            NSArray *array = [dic objectForKey:@"list"];
            if (array.count == 0) {
                
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索无效,请重新输入" preferredStyle: UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    
                }];
                
                [alert addAction:action];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                    
                }];
                
                
            } else {
                
                for (NSDictionary *dict in array) {
                    
                    ModelForSearch *model = [[ModelForSearch alloc] init];
                    
                    [model setValuesForKeysWithDictionary:dict];
                    
                    [self.array addObject:model];
                    
                    [model release];
                    
                }
            }
            [self.tableView reloadData];
            
            
        }];
        
    }
    
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    return self.array.count;
    
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CellForSearch *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForSearch"];
    
    ModelForSearch *model = [self.array objectAtIndex:indexPath.row];
    
    [cell passModelForSearch:model];
    
    // 带属性的字符串实现关键字高亮
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:model.origin_title];
    
    [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.origin_title rangeOfString:self.search.text]];
    [cell.labelForTitle setAttributedText:attribute];
    
    [attribute release];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    return self.view.frame.size.height / 8;
    
}

- (void)buttonAction {
    
    [self.navigationController popViewControllerAnimated:YES];
    
    //当点击 button 的时候让顶部的 view 和 button 隐藏同时进入上一个 vc
    self.viewForNail.hidden = YES;
    self.button.hidden = YES;
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.arrDict.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CollectionCellForCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForCollection" forIndexPath:indexPath];
    
    [cell passModelForHistory:[self.arrDict objectAtIndex:indexPath.item]];
    
    
    return cell;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
